package com.agriculture.utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class HttpUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    /**
     * 发送POST请求
     * @param url 请求URL
     * @param jsonBody JSON请求体
     * @return 响应字符串
     */
    public static String post(String url, String jsonBody) {
        logger.info("Sending POST request to URL: {}", url);
        logger.info("Request body: {}", jsonBody);

        RequestBody body = RequestBody.create(JSON, jsonBody);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body() != null ? response.body().string() : "";
            
            logger.info("Response status: {}", response.code());
            logger.info("Response body: {}", responseBody);
            logger.info("Response headers: {}", response.headers());
            
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response code: " + response + "\nResponse body: " + responseBody);
            }
            
            return responseBody;
        } catch (IOException e) {
            logger.error("HTTP request failed", e);
            throw new RuntimeException("HTTP request failed: " + e.getMessage());
        }
    }
} 